const mysql = require('mysql2/promise');

async function addNicknameColumn() {
  const connection = mysql.createConnection({
    host: '124.222.38.18',
    port: 3306,
    user: 'root',
    password: 'q13812833598',
    database: 'sbook'
  });

  try {
    console.log('连接数据库...');
    await connection.connect();

    console.log('检查nickname字段是否已存在...');
    const [rows] = await connection.execute(
      "SHOW COLUMNS FROM `users` WHERE Field = 'nickname'"
    );

    if (rows.length === 0) {
      console.log('nickname字段不存在，正在添加...');
      await connection.execute(
        "ALTER TABLE `users` ADD COLUMN `nickname` VARCHAR(100) NULL COMMENT '昵称' AFTER `username`"
      );
      console.log('nickname字段添加成功！');
    } else {
      console.log('nickname字段已存在');
    }

    // 验证字段是否添加成功
    const [verifyRows] = await connection.execute(
      "SHOW COLUMNS FROM `users` WHERE Field = 'nickname'"
    );

    if (verifyRows.length > 0) {
      console.log('验证成功：nickname字段已存在于users表中');
      console.log('字段信息：', verifyRows[0]);
    }

  } catch (error) {
    console.error('数据库操作失败:', error);
  } finally {
    await connection.end();
  }
}

addNicknameColumn();